import { View } from "@tarojs/components";
import { ContentForm } from "../../components/content-form";
import { useEffect, useState } from "react";
import ContentCard from "../../components/content-card";
import { AtDivider, AtFab, AtFloatLayout, AtMessage } from "taro-ui";
import Taro, { usePullDownRefresh, useReachBottom } from "@tarojs/taro";
import { observer } from "mobx-react";
import { infoStore } from "src/store/info";
import { SwipeAction } from "src/components/swipe-action";
import { MyButton } from "src/components/button/indx";

export const Activity = observer(() => {
  const [list, setList] = useState<
    { title: string; content: string; _id: string }[]
  >([]);
  const [showAdd, setShowAdd] = useState<{ title?: string; content?: string, _id?: string }>();
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [openId, setOpenId] = useState('')
  const { userInfo } = infoStore;

  const getList = async () => {
    Taro.showLoading({ title: "加载中" });
    if (!userInfo.nickName) return;
    const res = await Taro.cloud.callFunction({
      name: "activity",
      data: {
        type: "get",
        user: userInfo.nickName,
        page,
        size: 10,
      },
    });
    const { total, items } = (res as any).result;
    setList((list) => ([...list, ...items]));
    setTotal(total || 0);
    Taro.hideLoading();
    return res.result;
  };

  const refreshList = () => {
    if (page === 1) {
      getList();
    } else {
      setPage(1);
    }
  }

  usePullDownRefresh(() => {
    setList([]);
    refreshList()
  });

  useReachBottom(() => {
    if (list.length === total) return;
    setPage(page + 1);
  });

  useEffect(() => {
    if (page) {
      getList();
    }
  }, [page]);

  const addItem = async (item: { title: string; content: string }) => {
    if (!userInfo.nickName) return;
    const type = showAdd?._id? 'put' : 'post';
    await Taro.cloud.callFunction({
      name: "activity",
      data: {
        type,
        user: userInfo.nickName,
        ...showAdd,
        ...item,
      },
    });
    setShowAdd(undefined);
    Taro.atMessage({
      message: (type === 'post' ? '新增' : '编辑') + "成功",
      type: "success",
    });
    setList([]);
    refreshList();
  };

  const deleteItem = async (_id: string) => {
    await Taro.cloud.callFunction({
      name: "activity",
      data: {
        type: "delete",
        user: userInfo.nickName,
        _id,
      }
    });
    Taro.atMessage({
      message: "删除成功",
      type: "success",
    });
    setList([]);
    refreshList();
  }

  return (
    <View onClick={() => setOpenId('')}>
      <AtMessage />
      {list.map((item) => (
        <SwipeAction
          id={item._id}
          key={item._id}
          actions={
            <View onClick={(e) => e.stopPropagation()} style={{ display: "flex", height: '100%', alignItems: "center" }}>
              <MyButton style={{marginRight: 8}} circle type="primary" onClick={() => setShowAdd(item)}>编辑</MyButton>
              <MyButton circle type="danger" onClick={() => deleteItem(item._id)}>删除</MyButton>
            </View>
          }
          onMove={(flag) => setOpenId(flag? item._id : '')}
          open={openId === item._id}
        >
          <ContentCard title={item.title} content={item.content} />
        </SwipeAction>
      ))}
      {!!total && list.length === total && <AtDivider content="没有更多了" />}
      <AtFloatLayout
        isOpened={!!showAdd}
        title="新增记录"
        onClose={() => setShowAdd(undefined)}
      >
        <ContentForm visible={!!showAdd} editData={showAdd} onSubmit={addItem} />
      </AtFloatLayout>
      <View style={{ position: "fixed", right: "16px", bottom: "80px" }}>
        <AtFab onClick={() => setShowAdd({})} size="normal">
          新增
        </AtFab>
      </View>
    </View>
  );
});

export default Activity;
